package ink.tsg.javabase.netty;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOServer {
    public static void main(String[] args) throws IOException {
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动");
        while(true){
            // 监听等待客户端的连接
            final Socket accept = serverSocket.accept();
            System.out.println("连接到一个客户端");
            // 创建一个线程池
            newCachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    // 可以和客户端通信
                    handler(accept);
                }
            });
        }
    }

    public static void handler(Socket socket){
        System.out.println("当前线程："+Thread.currentThread().getId()+Thread.currentThread().getName());
        try{
            byte[] bytes = new byte[1024];
            InputStream inputStream = socket.getInputStream();
            // 读取客户端的数据
            while (true){
                int read = inputStream.read(bytes);
                if(read!=-1){
                    System.out.println(new String(bytes,0,read));
                }else {
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("关闭连接");
            try {
                socket.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

    }


}
